package com.example.cloudmaps;



import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.cloudmaps.Friends.GetFriendsTask;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.VisibleRegion;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner; 
import android.widget.Toast;

public class MainActivity extends FragmentActivity {

	private static final String PHP_LOC = "http://softeng.cs.uwosh.edu/students/meyers11/LngLtd.php";
	private static final String PHP_FRIENDLOC = "http://softeng.cs.uwosh.edu/students/meyers11/PHPGetFriendsLoc.php";
	private static final String PHP_CHECK = "http://softeng.cs.uwosh.edu/students/meyers11/PHPGetRequests.php";
	private static final String PHP_ADD = "http://softeng.cs.uwosh.edu/students/meyers11/PHPAddFriend.php";
	private static final String PHP_DELETE = "http://softeng.cs.uwosh.edu/students/meyers11/PHPDeleteRequest.php";
	private static final String PHP_FRIEND = "http://softeng.cs.uwosh.edu/students/meyers11/PHPGetFriends.php";
	private static final String PHP_GET = "http://softeng.cs.uwosh.edu/students/meyers11/PHPGetFavPlaces.php";
	private static final String PHP_ADD_FAV = "http://softeng.cs.uwosh.edu/students/meyers11/PHPAddPlaces.php";
	

	ArrayList<Friend> friends = new ArrayList<Friend>(); 
	ArrayList<Place> favPlaces = new ArrayList<Place>(); 
	double[] currentBounds = new double[4];
	ArrayList<Friend> friendswith = new ArrayList<Friend>(); 
	String username="";
	private String bestProvider;
	private Geocoder geocoder;
	private List<Address> user = null;
	final Context context = this;
	private Marker mark;
	private GoogleMap map;
	private Timer updateTimer;
	String tempsender = "";
	Location location;
	int viewTypeForMaps = map.MAP_TYPE_NORMAL;
	private int select = 0;
	
	//change these to users true location or "choose of destination"
	private double latitude = 0;
	private double longitude =0;
	private double marklat = 0;
	private double marklong = 0;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);


		// finding current position of user;
		double lat = 0; // set to default
		double lng = 0; // set to default

		new CheckRequestsTask().execute();

		try{
			LocationManager loactionManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
			Criteria criteria = new Criteria();
			bestProvider = loactionManager.getBestProvider(criteria,false);
			location = loactionManager.getLastKnownLocation(bestProvider);
		}
		catch(Exception e){
			System.out.println("Exception " + e);
		}


		if(location == null){
			Toast.makeText(this, "Location Not Found",  Toast.LENGTH_SHORT).show();
		}else{

			geocoder = new Geocoder(this);

			try{
				user = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
				lat = (double)user.get(0).getLatitude();
				lng = (double) user.get(0).getLongitude();
				
				//initalizing the global variables for lng and lat
				latitude = lat;
				longitude = lng;

				VisibleRegion boundaries = map.getProjection()
						.getVisibleRegion();
				LatLngBounds latlngBounds = boundaries.latLngBounds;
				LatLng ne = latlngBounds.northeast;
				LatLng sw = latlngBounds.southwest;
				currentBounds = new double[] { sw.latitude,
						sw.longitude, ne.latitude, ne.longitude };

			}catch(Exception e) {
				e.printStackTrace();
			}
		}

		map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
		map.setMyLocationEnabled(true);
		
		

		//finds the specific location via geocoder
		Location myLocation = map.getMyLocation();
		CameraUpdate center = 
				CameraUpdateFactory.newLatLng(new LatLng(lat, lng));                //new LatLng(40.76793169992044, -73.98184771729));
		CameraUpdate zoom = CameraUpdateFactory.zoomTo(15);

		//adjusts the map to the users location
		map.moveCamera(center);
		map.animateCamera(zoom);
		//End of finding current position

		//populate the map with nearbyplaces                  

		GooglePlaces googlePlaces = new GooglePlaces();
		List<MapPlaces> placesList = new ArrayList();
/*
		double longitude;
		double latitude;
		Marker markPlace;
		placesList = googlePlaces.nearbyPlaces(lat, lng);

		for(int i=1; i<placesList.size(); i++){

			longitude =   Double.parseDouble(placesList.get(i).getLng());
			latitude =  Double.parseDouble(placesList.get(i).getLat());
			LatLng locationOfPlace = new LatLng(latitude, longitude);

			markPlace = map.addMarker(new MarkerOptions()
			.position(locationOfPlace)
			.title(placesList.get(i).getName())); 
		}
		*/
		//end of for loop



		final Button send = (Button) findViewById(R.id.btnLocate);
		final EditText place = (EditText) findViewById(R.id.enterLocation);


		send.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				List<Address> destination = null;
				boolean success = false;
				double lat;
				double lng;
				geocoder = new Geocoder(getBaseContext(), Locale.getDefault());


				
				if(place.getText().toString().equals("")){
					Toast.makeText(MainActivity.this, "Type in a location", Toast.LENGTH_SHORT).show();
				}else{
					if(success)
					{
						mark.remove();
						success = false;
					}

					try{
						//  Toast.makeText(MainActivity.this, "made it here", Toast.LENGTH_SHORT).show();
						//  Toast.makeText(MainActivity.this, place.getText().toString(), Toast.LENGTH_SHORT).show();
						
						VisibleRegion boundaries = map.getProjection()
								.getVisibleRegion();
						LatLngBounds latlngBounds = boundaries.latLngBounds;
						LatLng ne = latlngBounds.northeast;
						LatLng sw = latlngBounds.southwest;
						currentBounds = new double[] { sw.latitude,
								sw.longitude, ne.latitude, ne.longitude };

						destination = geocoder.getFromLocationName(place.getText().toString(), 5,
								currentBounds[0],currentBounds[1],currentBounds[2],currentBounds[3]);

						lat = (double) destination.get(0).getLatitude();
						lng = (double) destination.get(0).getLongitude();
						
						latitude = lat;
						longitude = lng;
						
						location.setLatitude(lat);
						location.setLongitude(lat);
						
						user = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);

						LatLng place2 = new LatLng(lat, lng);
						mark = map.addMarker(new MarkerOptions()
						.position(place2)
						.title(place.getText().toString()));
						
						map.animateCamera(CameraUpdateFactory.newLatLng(place2));

						success = true;   						
					}catch(Exception e){
						e.printStackTrace();
					}
					if(!success)
						Toast.makeText(MainActivity.this, "Invaild Place", Toast.LENGTH_SHORT).show();

				}

			}

		});

		
		map.setOnInfoWindowClickListener(new OnInfoWindowClickListener(){

			@Override
			public void onInfoWindowClick(final Marker marker) {
				AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
				alertDialogBuilder.setTitle("Add To Favorite");
				alertDialogBuilder
				.setMessage("Is this a Favorite of yours?")
				.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,int id) {
						LatLng temp = marker.getPosition();
						marklat = temp.latitude;
						marklong = temp.longitude;
						
						
						new addToFavorites().execute(marker.getTitle().toString(), marker.getSnippet().toString());
						System.out.println("the dirty deed is done");
					}
				})
				.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,int id) {
						dialog.cancel();
					}
				});
				AlertDialog alertDialog = alertDialogBuilder.create();

				alertDialog.show();
			}
			
				
     	
     });


	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		// Handle item selection
		switch (item.getItemId()) {
		case R.id.clear_map:
			 map.clear();
				new GetFriendsTask().execute();
				new GetFavPlaces().execute();
			return true;
		case R.id.action_logout:
			new Logout().execute();
			Intent myIntent3 = new Intent(MainActivity.this, LoginActivity.class);
			startActivityForResult(myIntent3, 0);
			MainActivity.this.finish();
			return true;
		case R.id.action_friends:
			if(username.equals("skip")){
				AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
				alertDialogBuilder.setTitle("Cloud Maps");

				alertDialogBuilder
				.setMessage("You Need to Log in Before Managing Friends!")
				.setPositiveButton("Ok",new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,int id) {
						Intent myIntent4 = new Intent(MainActivity.this, LoginActivity.class);
						startActivityForResult(myIntent4, 0);
						MainActivity.this.finish();
						dialog.cancel();
					}
				})
				.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,int id) {
						dialog.cancel();
					}
				});

				AlertDialog alertDialog = alertDialogBuilder.create();

				alertDialog.show();
			}
			else{
				Intent myIntent4 = new Intent(MainActivity.this, Friends.class);
				startActivityForResult(myIntent4, 0);
				MainActivity.this.finish();
			}
			return true;
		case R.id.action_login:
			Intent myIntent5 = new Intent(MainActivity.this, LoginActivity.class);
			if (username.equals("skip")){
				startActivityForResult(myIntent5, 0);
				MainActivity.this.finish();
			}
			else{
				AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
				alertDialogBuilder.setTitle("Cloud Maps");

				alertDialogBuilder
				.setMessage("You are already Logged in!")
				.setPositiveButton("Ok",new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,int id) {
						dialog.cancel();
					}
				});

				AlertDialog alertDialog = alertDialogBuilder.create();

				alertDialog.show();
			}
			return true;
		case R.id.satOrNorm: 
			if(map.MAP_TYPE_SATELLITE == viewTypeForMaps){
				map.setMapType(map.MAP_TYPE_NORMAL);
				viewTypeForMaps = map.MAP_TYPE_NORMAL;
			}else{
				map.setMapType(map.MAP_TYPE_SATELLITE);
				viewTypeForMaps = map.MAP_TYPE_SATELLITE;
			}
			return true;
		case R.id.point_of_interest:
			final String elements [] = {"gym", "food", "store", "bar", "parking"};
			
			AlertDialog.Builder builder = new AlertDialog.Builder(this).setTitle("Point of Intrest");
        	
        	builder.setSingleChoiceItems(
                    elements,
                    select,
                    new DialogInterface.OnClickListener() {
                 
                @Override
                public void onClick(
                        DialogInterface dialog,
                        int which) {
                    select = which;
                }
            })
            .setCancelable(false)
            .setPositiveButton("OK",
                new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog,
                            int which) {
                      locatePointOfIntrest(elements[select]);
                                
                    }
                });
        	
        	AlertDialog alert = builder.create();
            alert.show();
			
			return true;
		case R.id.true_location:
			Double lat=0.0;
			Double lng=0.0;
			try{
				LocationManager loactionManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
				Criteria criteria = new Criteria();
				bestProvider = loactionManager.getBestProvider(criteria,false);
				location = loactionManager.getLastKnownLocation(bestProvider);
			}
			catch(Exception e){
				System.out.println("Exception " + e);
			}
			try{
				user = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
				lat = (double)user.get(0).getLatitude();
				lng = (double) user.get(0).getLongitude();
				
				//initalizing the global variables for lng and lat
				latitude = lat;
				longitude = lng;

				VisibleRegion boundaries = map.getProjection()
						.getVisibleRegion();
				LatLngBounds latlngBounds = boundaries.latLngBounds;
				LatLng ne = latlngBounds.northeast;
				LatLng sw = latlngBounds.southwest;
				currentBounds = new double[] { sw.latitude,
						sw.longitude, ne.latitude, ne.longitude };

			}catch(Exception e) {
				e.printStackTrace();
			}
			
			map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
			map.setMyLocationEnabled(true);


			//adjusts the map to the users location
			map.animateCamera(CameraUpdateFactory.newLatLng(new LatLng(lat, lng)));
			
			return true;
		case R.id.manage_places:
			if(username.equals("skip")){
				AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
				alertDialogBuilder.setTitle("Cloud Maps");

				alertDialogBuilder
				.setMessage("You Need to Log in Before Managing Places!")
				.setPositiveButton("Ok",new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,int id) {
						Intent myIntent4 = new Intent(MainActivity.this, LoginActivity.class);
						startActivityForResult(myIntent4, 0);
						MainActivity.this.finish();
						dialog.cancel();
					}
				})
				.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,int id) {
						dialog.cancel();
					}
				});

				AlertDialog alertDialog = alertDialogBuilder.create();

				alertDialog.show();
			}
			else{
				Intent myIntent4 = new Intent(MainActivity.this, FavoritePlaces.class);
				startActivityForResult(myIntent4, 0);
				MainActivity.this.finish();
			}
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
	
	public void locatePointOfIntrest(String str){
		InterestPlaces ip = new InterestPlaces();
		List<MapPlaces> placesList = ip.nearbyPlaces(latitude, longitude, str);
		Marker markPlace;
		
		for(int i =0; i<placesList.size(); i++){
			double longitude =   Double.parseDouble(placesList.get(i).getLng());
	    	double latitude =  Double.parseDouble(placesList.get(i).getLat());
			 LatLng locationOfPlace = new LatLng(latitude, longitude);
			   
			   markPlace = map.addMarker(new MarkerOptions()
			   								.position(locationOfPlace)
			   								.title(placesList.get(i).getName())
			   								.snippet(placesList.get(i).getAddr())); 
			  
		}
	}

	@Override
	protected void onResume(){
		super.onResume();
		new getLoginInfo().execute();

		updateTimer = new Timer();
		updateTimer.schedule(new TimerTask(){
			@Override
			public void run(){
				new CheckRequestsTask().execute();
			}
		}, 10000, 10000);

		//Get Friend markers
		new GetFriendsTask().execute();
		//Get Fav Places Markers
		System.out.println("RESUME CALL");
		new GetFavPlaces().execute();

	}

	//Get Login Info
	private class getLoginInfo extends AsyncTask<Void, Void, String>{
		@Override
		protected String doInBackground(Void... nothing) {

			MapDataSource mds2 = new MapDataSource(MainActivity.this);

			mds2.open();

			try {
				username = mds2.getUsername();
			} catch (Exception e) {
				e.printStackTrace();
			}

			mds2.close();

			return username;
		}

		@Override
		protected void onPostExecute(String whatever) {
			if (username.equals("user")){
				Intent myIntent = new Intent(MainActivity.this, LoginActivity.class);
				startActivityForResult(myIntent, 0);
				return;
			}
			else{
				return;
			}
		}
	}

	//Logout
	private class Logout extends AsyncTask<Void, Void, String>{
		@Override
		protected String doInBackground(Void... nothing) {

			MapDataSource mds2 = new MapDataSource(MainActivity.this);

			mds2.open();

			try {
				mds2.logoutUser();
			} catch (Exception e) {
				e.printStackTrace();
			}

			mds2.close();

			return "";
		}

		@Override
		protected void onPostExecute(String whatever) {
			Intent myIntent = new Intent(MainActivity.this, LoginActivity.class);
			startActivityForResult(myIntent, 0);
			MainActivity.this.finish();
		}

	}

	public class UserCoordinates extends AsyncTask<String,String, Boolean> 
	{
		protected Boolean doInBackground(String... params)
		{
			Boolean success = false;
			ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

			if(networkInfo != null && networkInfo.isConnected())
			{
				ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>(1);
				nvp.add(new BasicNameValuePair("username", username));
				nvp.add(new BasicNameValuePair("latitude", params[0]));
				nvp.add(new BasicNameValuePair("longitude", params[1]));

				HttpClient httpClient = new DefaultHttpClient();
				HttpPost httpPost = new HttpPost(PHP_LOC);

				try
				{
					httpPost.setEntity(new UrlEncodedFormEntity(nvp));
					ResponseHandler<String> respondHandler = new BasicResponseHandler();
					String response = httpClient.execute(httpPost, respondHandler);
					success = true;
				}catch(Exception e){
					System.out.println("coordinates failed");
				}
			}
			return success;
		}

	}

	public class GetFriendCoords extends AsyncTask<String,Void, String> 
	{
		protected String doInBackground(String... params)
		{	
			String success = "";
			ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

			if(networkInfo != null && networkInfo.isConnected())
			{
				ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>(1);
				System.out.println("lol" + params[0] + "lol");
				nvp.add(new BasicNameValuePair("username", params[0]));

				HttpClient httpClient = new DefaultHttpClient();
				HttpPost httpPost = new HttpPost(PHP_FRIENDLOC);

				try
				{
					httpPost.setEntity(new UrlEncodedFormEntity(nvp));
					ResponseHandler<String> respondHandler = new BasicResponseHandler();
					String response = httpClient.execute(httpPost, respondHandler);

					Double longit=0.0;
					Double lat=0.0;

					try{

						JSONArray jArray = new JSONArray(response);

						JSONObject json_data = null;

						for(int i = 0; i < jArray.length(); i++)
						{
							json_data = jArray.getJSONObject(i);

							longit = Double.valueOf(json_data.getString("longitude"));
							lat = Double.valueOf(json_data.getString("latitude"));


							for(Friend f : friends){
								if (f.getUsername().equals(params[0])){
									f.setLogitude(longit);
									f.setLatitude(lat);
								}
							}
						}

					}catch(JSONException e){
						e.printStackTrace();
						System.out.println("json parser failed" + e);
					}

					success = "true";
				}catch(Exception e){
					System.out.println("coordinates failed");
				}
			}
			return success;
		}
		@Override
		protected void onPostExecute(String whatever) {
			if(!whatever.equals("false")){
				for(Friend f : friends){
					System.out.println("USERNAME " + f.getUsername() + " " + f.getLatitude() + " " + f.getLongitude());
					Marker markPlace;
					double longitude;
					double latitude;
					longitude = f.getLongitude();
					latitude =  f.getLatitude();
					LatLng locationOfFriend = new LatLng(latitude, longitude);

					map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

					map.addMarker(new MarkerOptions()
					.position(new LatLng(f.getLatitude(), f.getLongitude()))
					.title(f.getUsername())
					.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))); 
				}
			}
		}		
	}
	
	
	public class GetFavPlaces extends AsyncTask<Void,Void, String> {
	@Override
	protected String doInBackground(Void... params) {
		// TODO: attempt authentication against a network service.
		String response = "";
		String success = "";
		ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
		
		if(networkInfo != null && networkInfo.isConnected())
		{
			ArrayList<NameValuePair> n = new ArrayList<NameValuePair>(1);
			n.add(new BasicNameValuePair("username", username));
			
			HttpClient httpClient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(PHP_GET);
			try
			{
				httppost.setEntity(new UrlEncodedFormEntity(n));
				ResponseHandler<String> respondHandler = new BasicResponseHandler();
				response = httpClient.execute(httppost, respondHandler);
				
				String name2 = "";
				String address = "";
				String la = "";
				String lo = "";
				Double lat=0.0;
				Double longit=0.0;
				
				try{

					JSONArray jArray = new JSONArray(response);
					
					JSONObject json_data = null;

					for(int i = 0; i < jArray.length(); i++)
					{
						json_data = jArray.getJSONObject(i);
						
						
						name2 = json_data.getString("name");
						address = json_data.getString("address");
						lo = json_data.getString("longitude");
						la = json_data.getString("latitude");
						
						lat  = Double.valueOf(la);
						longit = Double.valueOf(lo);
						
						
						
						System.out.println("RESUME STUFF " + name2 + " address");
						Place tempplace = new Place(name2,address,lat,longit);
						

						favPlaces.add(tempplace);
					}
					
				}catch(JSONException e1){
					e1.printStackTrace();
					System.out.println("RESUME json parser" + e1);
				}
			}
			catch(Exception e){
				System.out.println("RESUME jarray " + e);
			}
		}
		
		return success;
	}
		@Override
		protected void onPostExecute(String whatever) {
			if(!whatever.equals("false") && favPlaces.size() != 0){
				for(Place p : favPlaces){
					String name = "";
					String address = "";
					name = p.getName();
					address = p.getAddress();
					
					System.out.println("RESUME MARK THIS " + name + " " + address + " " + p.getLatitude() + " " + p.getLongitude());

					map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

					map.addMarker(new MarkerOptions()
					.position(new LatLng(p.getLatitude(), p.getLongitude()))
					.title(name)
					.snippet(address)
					.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))); 
				}
			}
		}		
	}



	public class CheckRequestsTask extends AsyncTask<Void, Void, ArrayList<Request>> {
		@Override
		protected ArrayList<Request> doInBackground(Void... params) {
			// TODO: attempt authentication against a network service.
			String response = "";
			ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

			ArrayList<Request> requests = new ArrayList<Request>(); 

			if(networkInfo != null && networkInfo.isConnected())
			{
				ArrayList<NameValuePair> n = new ArrayList<NameValuePair>(1);
				n.add(new BasicNameValuePair("receiver", username));

				HttpClient httpClient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost(PHP_CHECK);
				try
				{
					httppost.setEntity(new UrlEncodedFormEntity(n));
					ResponseHandler<String> respondHandler = new BasicResponseHandler();
					response = httpClient.execute(httppost, respondHandler);

					try{

						JSONArray jArray = new JSONArray(response);

						JSONObject json_data = null;

						for(int i = 0; i < jArray.length(); i++)
						{
							json_data = jArray.getJSONObject(i);

							String sender = "";

							sender = json_data.getString("sender");

							Request requestTemp = new Request(sender,username);
							requests.add(requestTemp);
						}

					}catch(JSONException e1){
						e1.printStackTrace();
					}
				}
				catch(Exception e){

				}
			}
			return requests;
		}

		@Override
		protected void onPostExecute(ArrayList<Request> resp){
			//display friend requests

			for(Request r : resp){
				tempsender = r.getSender();

				if (!tempsender.equals("")){


					AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
					alertDialogBuilder.setTitle("You Have a Friend Request!");

					alertDialogBuilder
					.setMessage(tempsender + " would like to add you as a friend")
					.setPositiveButton("Accept",new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,int id) {
							System.out.println("ADD" + tempsender + username);
							new addFriend().execute(tempsender,username);
							new deleteRequest().execute(tempsender,username);
							dialog.cancel();
						}
					})
					.setNegativeButton("Decline",new DialogInterface.OnClickListener(){
						public void onClick(DialogInterface dialog,int id) {
							System.out.println("Negative Button clicked");
							new deleteRequest().execute(tempsender,username);
							dialog.cancel();
						}
					});

					AlertDialog alertDialog = alertDialogBuilder.create();

					alertDialog.show();
				}
			}

			new UserCoordinates().execute(Double.toString(location.getLatitude()),Double.toString(location.getLongitude()));

		}

	}

	public class addFriend extends AsyncTask<String,String, Boolean> 
	{
		protected Boolean doInBackground(String... params)
		{

			Boolean success = false;
			ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

			if(networkInfo != null && networkInfo.isConnected())
			{
				ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>(1);
				nvp.add(new BasicNameValuePair("sender", params[0]));
				nvp.add(new BasicNameValuePair("receiver", params[1]));

				HttpClient httpClient = new DefaultHttpClient();
				HttpPost httpPost = new HttpPost(PHP_ADD);

				try
				{
					httpPost.setEntity(new UrlEncodedFormEntity(nvp));
					ResponseHandler<String> respondHandler = new BasicResponseHandler();
					String response = httpClient.execute(httpPost, respondHandler);
					success = true;
				}catch(Exception e){
					System.out.println("Add friend failed");
				}
			}
			return success;
		}

	}

	public class deleteRequest extends AsyncTask<String,String, Boolean> 
	{
		protected Boolean doInBackground(String... params)
		{
			System.out.println("HELLO");
			Boolean success = false;
			ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

			if(networkInfo != null && networkInfo.isConnected())
			{
				ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>(1);
				nvp.add(new BasicNameValuePair("sender", params[0]));
				nvp.add(new BasicNameValuePair("receiver", params[1]));

				HttpClient httpClient = new DefaultHttpClient();
				HttpPost httpPost = new HttpPost(PHP_DELETE);

				try
				{
					httpPost.setEntity(new UrlEncodedFormEntity(nvp));
					ResponseHandler<String> respondHandler = new BasicResponseHandler();
					String response = httpClient.execute(httpPost, respondHandler);
					success = true;
				}catch(Exception e){
					System.out.println("Delete Request failed");
				}
			}
			return success;
		}

	}

	public class GetFriendsTask extends AsyncTask<Void, Void, String> {
		@Override
		protected String doInBackground(Void... params) {
			// TODO: attempt authentication against a network service.
			String response = "";
			ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

			if(networkInfo != null && networkInfo.isConnected())
			{
				ArrayList<NameValuePair> n = new ArrayList<NameValuePair>(1);
				n.add(new BasicNameValuePair("username1", username));

				HttpClient httpClient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost(PHP_FRIEND);
				try
				{
					httppost.setEntity(new UrlEncodedFormEntity(n));
					ResponseHandler<String> respondHandler = new BasicResponseHandler();
					response = httpClient.execute(httppost, respondHandler);

					try{

						JSONArray jArray = new JSONArray(response);

						JSONObject json_data = null;

						for(int i = 0; i < jArray.length(); i++)
						{
							json_data = jArray.getJSONObject(i);

							String username2 = "";

							username2 = json_data.getString("username2");

							Friend temp = new Friend();

							temp.setUsername(username2);

							friends.add(temp);
						}

					}catch(JSONException e1){
						e1.printStackTrace();
					}
				}
				catch(Exception e){

				}
			}
			return response;

		}
		@Override
		protected void onPostExecute(String whatever) {
			if(!whatever.equals("false")){
				for(Friend f : friends){
					System.out.println("FRIENDS " + f.getUsername());
					new GetFriendCoords().execute(f.getUsername());
				}
			}
		}
	}
	
	public class addToFavorites extends AsyncTask<String,String, Boolean> 
	{
		protected Boolean doInBackground(String... params)
		{
			Boolean success = false;
			ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

			if(networkInfo != null && networkInfo.isConnected())
			{
				ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>(1);
				String lng = marklong +"";
				String lat = marklat +"";
				lng.trim();
				
				nvp.add(new BasicNameValuePair("longitude", lng));
				nvp.add(new BasicNameValuePair("latitude", lat));
				nvp.add(new BasicNameValuePair("name", params[0]));
				nvp.add(new BasicNameValuePair("address", params[1]));
				nvp.add(new BasicNameValuePair("username", username));

				HttpClient httpClient = new DefaultHttpClient();
				HttpPost httpPost = new HttpPost(PHP_ADD_FAV);

				try
				{
					httpPost.setEntity(new UrlEncodedFormEntity(nvp));
					ResponseHandler<String> respondHandler = new BasicResponseHandler();
					String response = httpClient.execute(httpPost, respondHandler);
					success = true;
				}catch(Exception e){
					System.out.println("Add failed");
				}
			}
			return success;
		}

	}

	}
